const db = require('../db/index')
const util = require('util')
const query = util.promisify(db.query).bind(db)

function getTree(results, keyId) {
    //生成一级菜单
    let arr = []
    for (idx in results) {
        if (results[idx].ps_level == 0) {
            if (keyId.length !== 0 && keyId.indexOf(results[idx].ps_id + '') == -1) {
                continue
            }
            arr.push({
                "id": results[idx].ps_id,
                "authName": results[idx].ps_name,
                "path": results[idx].ps_api_path,
                "pid": results[idx].ps_pid,
                "children": []
            })
        }
    }
    // 生成二级菜单
    for (idx in results) {
        if (results[idx].ps_level == 1) {
            for (var j = 0; j < arr.length; j++) {
                if (results[idx]['ps_pid'] == arr[j].id) {
                    if (keyId.length !== 0 && keyId.indexOf(results[idx].ps_id + '') == -1) {
                        continue
                    }
                    arr[j].children.push({
                        "id": results[idx].ps_id,
                        "authName": results[idx].ps_name,
                        "path": results[idx].ps_api_path,
                        "pid": results[idx].ps_pid,
                        "children": []
                    })
                }
            }
        }
    }
    // 生成三级菜单
    for (idx in results) {
        if (results[idx].ps_level == 2) {
            for (var j = 0; j < arr.length; j++) {
                for (var i = 0; i < arr[j].children.length; i++) {
                    if (results[idx]['ps_pid'] == arr[j].children[i].id) {
                        if (keyId.length !== 0 && keyId.indexOf(results[idx].ps_id + '') == -1) {
                            continue
                        }
                        arr[j].children[i].children.push({
                            "id": results[idx].ps_id,
                            "authName": results[idx].ps_name,
                            "path": results[idx].ps_api_path,
                            "pid": results[idx].ps_pid + ',' + arr[j].id,
                        })
                    }
                }
            }

        }
    }
    return arr
}
exports.rightList = (req, res) => {
    // res.ResData("获取权限列表")
    //接收参数
    const type = req.params.type
        // console.log(type);
        // 判断参数类型
    if (!type || type != 'list' && type != 'tree')
        return res.ResData("参数错误")
    var sql = "select a.ps_id,a.ps_name,a.ps_pid,a.ps_level,b.ps_api_path FROM sp_permission a LEFT JOIN sp_permission_api b ON(a.ps_id=b.ps_id)"
    db.query(sql, (err, results) => {
        if (err) res.ResData("获取列表失败")
        if (type == 'list') {
            var arr = []
            for (idx in results) {
                const result = results[idx];
                arr.push({
                    "id": result.ps_id,
                    "authName": result.ps_name,
                    "level": result.ps_level,
                    "pid": result.ps_pid,
                    "path": result.ps_api_path
                })
            }
            res.ResData("获取权限列表成功", 200, arr)
        } else {
            let tree = getTree(results, [])
                // console.log(tree);
            res.ResData("获取权限列表成功", 200, tree)
        }
    })
}
exports.rolesList = async(req, res) => {
        // res.ResData("角色列表")
        var sql1 = "select * from sp_role"
        var sql2 = "select a.ps_id,a.ps_name,a.ps_pid,a.ps_level,b.ps_api_path FROM sp_permission a LEFT JOIN sp_permission_api b ON(a.ps_id=b.ps_id)"
        try {
            var result1 = await query(sql1)
            var result2 = await query(sql2)
            let arr = []
            for (idx in result1) {
                let keyId = result1[idx]['ps_ids'].split(",")
                let obj = {
                    "id": result1[idx].role_id,
                    "roleName": result1[idx].role_name,
                    "roleDesc": result1[idx].role_desc,
                    "children": []
                }
                let tree = getTree(result2, keyId)
                    // console.log(tree);
                obj.children = tree
                arr.push(obj)
            }
            res.ResData('获取权限列表成功', 200, arr)
        } catch (err) {
            res.ResData(err)
        }
    }
    // 更新角色
exports.updateRoleRights = (req, res) => {
        // res.ResData('更新角色')
        // 获取角色的id
        const roleId = req.params.roleId
            // console.log(roleId);
            // 参数验证
        if (roleId.trim() == '') return res.ResData("角色Id不能为空")
            // if (parseInt(roleId) != roleId) return res.ResData("角色Id必须是整数")
        if (roleId.indexOf('.') != -1) return res.ResData("角色Id必须是整数")
        if (parseInt(roleId) != roleId) return res.ResData("角色Id必须是数字")
        var sql = "update sp_role set ps_ids=? where role_id=?"
        db.query(sql, [req.body.rids, roleId], (err, result) => {
            if (err) return res.ResData("角色授权失败")
            res.ResData("更新成功", 200)
        })
    }
    // 添加角色
exports.addRoles = (req, res) => {
        // console.log(123);
        var role_name = req.body.roleName
        var role_desc = req.body.roleDesc
            // 检查Id是否存在
        var sql = "select * from sp_role where role_name=?"
        db.query(sql, role_name, (err, data) => {
                if (err) return res.ResData("添加失败")
                if (data.length > 0) {
                    return res.ResData("角色名已经存在")
                }
                var sql = "insert into sp_role (role_name,role_desc) values (?,?)"
                db.query(sql, [role_name, role_desc], (err, result) => {
                    if (err) return res.ResData("添加失败")
                    res.ResData("添加数据成功", 200, {
                        "roleName": role_name,
                        "roleDesc": role_desc
                    })
                })
            })
            // 添加数据

    }
    // 根据 ID 查询角色
exports.searchRoles = (req, res) => {
        // console.log(123);
        var id = req.params.id
            // console.log(id);
        var sql = "select * from sp_role where role_id=?"
        db.query(sql, id, (err, result) => {
            if (err) return res.ResData("角色获取失败")
            if (result.length > 0) {
                res.ResData("获取成功", 200, {
                    "roleId": result[0].role_id,
                    "roleName": result[0].role_name,
                    "roleDesc": result[0].role_desc
                })
            }
        })
    }
    // 删除角色指定权限
exports.deleteRoleRight = (req, res) => {
        // console.log('123');
        // 参数验证
        const roleId = req.params.roleId
            // 获取权限id
        const rightId = req.params.rightId
            // console.log(roleId);
            // 参数验证
        if (roleId.trim() == '') return res.ResData("角色Id不能为空")
        if (roleId.indexOf('.') != -1) return res.ResData("角色Id必须是整数")
        if (parseInt(roleId) != roleId) return res.ResData("角色Id必须是数字")

        if (rightId.trim() == '') return res.ResData("角色Id不能为空")
        if (rightId.indexOf('.') != -1) return res.ResData("权限Id必须是整数")
        if (parseInt(rightId) != rightId) return res.ResData("权限Id必须是数字")
        var sql = "select * from sp_role where role_id=?"
        db.query(sql, roleId, (err, result) => {
            if (err) return res.ResData('获取角色信息失败')
                // console.log(result);
            ps_ids = result[0].ps_ids.split(',')
                // console.log(ps_ids);
            new_ps_ids = []
            for (ids in ps_ids) {
                ps_id = ps_ids[ids]
                if (rightId == ps_id) {
                    continue
                }
                new_ps_ids.push(ps_id)
            }
            // 把删除后的数组转成字符串
            news_ps_ids = new_ps_ids.join(',')
                // console.log(new_ps_ids);
                // 更新数据
            var sql = "update sp_role set ps_ids=? where role_id=?"
            db.query(sql, [news_ps_ids, roleId], (err, data) => {
                if (err) return res.ResData('删除失败')
                var sql2 = "select a.ps_id,a.ps_name,a.ps_pid,a.ps_level,b.ps_api_path FROM sp_permission a LEFT JOIN sp_permission_api b ON(a.ps_id=b.ps_id)"
                db.query(sql2, (err, data1) => {
                    let tree = getTree(data1, new_ps_ids)
                        // console.log(tree);
                    res.ResData("删除成功", 200, tree)
                })

            })
        })
    }
    // 编辑提交角色
exports.updateRole = (req, res) => {
        // console.log('123');
        var role_id = req.params.id
        var role_name = req.body.roleName
        var role_desc = req.body.roleDesc
            // 更新数据
        var sql = "update sp_role set role_name=?,role_desc=? where role_id=?"
        db.query(sql, [role_name, role_desc, role_id], (err, result) => {
            // console.log(result);
            if (err) return res.ResData('更新角色信息失败')
            console.log(result);
            if (result.affectedRows < 1) {
                return res.ResData('更新角色信息失败')
            }
            var sql = "select * from sp_role where role_id=?"
            db.query(sql, role_id, (err, data) => {
                res.ResData('获取成功', 200, {
                    "roleId": data[0].role_id,
                    "roleName": data[0].role_name,
                    "roleDesc": data[0].role_desc
                })
            })
        })

    }
    // 删除角色
exports.deleteRole = (req, res) => {
    // console.log(123);
    var role_id = req.params.id
    var sql = "delete from sp_role where role_id=?"
    db.query(sql, role_id, (err, result) => {
        if (err) return res.ResData('删除失败')
        if (result.affectedRows != 1) return res.ResData('删除失败')
        res.ResData('删除成功', 200)
    })
}